package com.duojuhe.common.utils.encryption.aes;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;


/**
 * AES工具类
 * https://tool.lmeee.com/jiami/aes
 */
public class AESUtil {
    // 偏移量
    private final static int offset = 16;
    private final static String transformation = "AES/CBC/PKCS5Padding";
    private final static String algorithm = "AES";

    /**
     * 加密
     *
     * @param content
     *            需要加密的内容
     * @param key
     *            加密密码
     * @return
     */
    public static String encrypt(String content, String key) {
        try {
            if (StringUtils.isBlank(content)||StringUtils.isBlank(key)){
                return "";
            }
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), algorithm);
            IvParameterSpec iv = new IvParameterSpec(key.getBytes(), 0, offset);
            Cipher cipher = Cipher.getInstance(transformation);
            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
            cipher.init(Cipher.ENCRYPT_MODE, skey, iv);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return new Base64().encodeToString(result); // 加密
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * AES（256）解密
     *
     * @param content
     *            待解密内容
     * @param key
     *            解密密钥
     * @return 解密之后
     * @throws Exception
     */
    public static String decrypt(String content, String key) {
        try {
            if (StringUtils.isBlank(content)||StringUtils.isBlank(key)){
                return "";
            }
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), algorithm);
            IvParameterSpec iv = new IvParameterSpec(key.getBytes(), 0, offset);
            Cipher cipher = Cipher.getInstance(transformation);
            cipher.init(Cipher.DECRYPT_MODE, skey, iv);// 初始化
            byte[] result = cipher.doFinal(new Base64().decode(content));
            return new String(result); // 解密
        } catch (Exception e) {
            return "";
        }
    }

    public static void main(String[] args) throws Exception {
        String s = "00f6355486ed4a9c9694f0fb448832c4";
        String key = "9875565698752314";

        // 加密
        System.out.println("加密前：" + s);
        String encryptResultStr = encrypt(s,key);
        System.out.println("加密后：" + encryptResultStr);


        // 解密
        System.out.println("解密后：" + decrypt("CKVxW1RWNycri+Sh4gmJxFc5qaA/iXiupHgJj/yXj2r4LRpN/fsG81A/290owO7l",key));
    }
}